package com.iweb.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iweb.user.model.User;
import com.iweb.user.mapper.UserMapper;
import com.iweb.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jack
 * @since 2024-09-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource(name = "lockRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private UserMapper userMapper;


    @Override
    public void saveUser(User user) throws Exception {
        String key = "insert:" + user.getPhone();
        try {
            // do while  等待锁释放
            if (Boolean.FALSE.equals(redisTemplate.opsForValue().setIfAbsent(key, "1", Duration.ofMillis(20000)))) {
                throw new RuntimeException("手机号已注册");
            }
            // 查询 手机号是否使用
            int count = userMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getPhone, user.getPhone()));
            if (count >= 1) {
                throw new RuntimeException("手机号已注册");
            }
            /*可能查询后, 还没有插入的时候其他线程使用这个手机号*/
            // 插入 user
            userMapper.insert(user);
            Thread.sleep(100000);
        } finally {
            // 释放锁
            redisTemplate.delete(key);
        }

    }
}
